package com.atguigu.servlet;

import sun.misc.BASE64Encoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * Date:2020/9/18
 * Author:ybc
 * Description:
 */
public class DownServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //获取请求参数，即下载的文件名
        String musicName = request.getParameter("musicName");
        //1、获取下载的文件的类型
        String musicPath = request.getServletContext().getRealPath("music") + File.separator + musicName;
        String mimeType = request.getServletContext().getMimeType(musicPath);
        //将下载的文件类型设置为响应的内容格式
        response.setContentType(mimeType);
        //处理浏览器不能解析中文的问题
        String ua = request.getHeader("User-Agent");
        //判断客户端是否为火狐
        if(ua.contains("Firefox")){
            //若为火狐使用BASE64编码
            musicName = "=?utf-8?B?"+new BASE64Encoder()
                    .encode(musicName.getBytes("utf-8"))+"?=";
        }else{
            //否则使用UTF-8
            musicName = URLEncoder.encode(musicName,"utf-8");
        }
        //2、设置下载方式，attachment代表以附件的方式进行下载，filename设置下载的文件默认名称
        response.setHeader("Content-Disposition", "attachment; filename="+ musicName);
        //3、文件复制
        InputStream is = new FileInputStream(musicPath);
        ServletOutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int read = 0;
        while((read = is.read(b)) != -1){
            os.write(b, 0, read);
        }
        os.close();
        is.close();
    }
}
